const mongoose = require('mongoose');

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGODB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });

    console.log(`✅ MongoDB 连接成功: ${conn.connection.host}`);
    
    // 监听连接错误
    mongoose.connection.on('error', (err) => {
      console.error('❌ MongoDB 连接错误:', err);
    });

    // 监听连接断开
    mongoose.connection.on('disconnected', () => {
      console.log('⚠️  MongoDB 连接断开');
    });

  } catch (error) {
    console.error('❌ MongoDB 连接失败:', error.message);
    console.log('💡 提示: 请确保MongoDB服务已启动');
    console.log('   - Windows: 运行 "net start MongoDB" 或启动MongoDB服务');
    console.log('   - 或安装MongoDB Community Server: https://www.mongodb.com/try/download/community');
    // 不退出进程，允许在没有MongoDB的情况下启动服务器（便于开发）
    // process.exit(1);
  }
};

module.exports = connectDB;
